package com.mzj.saas.jobs.backlog.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.jobs.backlog.entity.BacklogItem;
import com.mzj.saas.jobs.backlog.entity.BacklogItemContract;
import com.mzj.saas.jobs.backlog.repository.BacklogItemContractRepository;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRepository;
import com.mzj.saas.jobs.redis.RedisService;

/**
 * 待办事项
 */
@Service
public class BacklogService {
    private static Logger log = LoggerFactory.getLogger(BacklogService.class);
    
    @Value("${saas.service}")
	private String saasService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService; 
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemContractRepository backlogItemContractRepository;
    
    public String work() throws Exception {
    	handleContractBacklog();
        return "SUCCESS";
    }
    
    /**
     * 检查合同到期提醒到待办事项
     */
    public void handleContractBacklog(){
    	try {
    		
            //默认一个月
    	    Integer expiredDay = 31;
    	    
    	    String expiredStr = redisService.getValue(Constant.CONTRACT_EXPIRED_DAY);
    		 
    	    if(StringUtils.isNotBlank(expiredStr)) {
    	    	expiredDay = Integer.parseInt(expiredStr);
    	    }
    	    
    	    log.info("BacklogService----->提前{}天,合同到期提醒",expiredDay);
    	    
            
            String sql = "SELECT h.id,h.org_id AS orgId,h.contract_number as contractNumber,STR_TO_DATE(c.ent_time,'%Y-%m-%d') AS entTime,c.match_user_id AS matchUserId FROM saas_house h \n" + 
            		"LEFT JOIN saas_house_contract c ON h.contract_number = c.contract_nubmer WHERE match_status = 2 \n" + 
            		"AND STR_TO_DATE(NOW(),'%Y-%m-%d') = STR_TO_DATE(DATE_SUB(c.ent_time ,INTERVAL ? DAY),'%Y-%m-%d')";
    		
            List<Map<String,Object>> infoList =  jdbcTemplate.queryForList(sql,expiredDay);
            
            if(CollectionUtils.isEmpty(infoList)) {
            	 log.info("BacklogService----->还没有合同到期,无需提醒");
            	 return;
            }
            
            log.info("BacklogService----->合同到期提醒 size = {}",infoList.size());
            Date date = new Date();
            infoList.forEach(info->{
            	
            	String content = "合同即将到期，请及时联系产权所有人续租，请在"+info.get("entTime")+"前续租";
            	BacklogItem item = new BacklogItem();
            	item.setHouseId(info.get("id").toString());
            	item.setOrgId(Long.parseLong(info.get("orgId").toString()));
            	item.setTitle("合同到期提醒");
            	item.setContent(content);
            	item.setBusinessStatus("(合同)到期提醒");
            	item.setType(BacklogItemTypeEnum.CONTRACT_OVERDUE.getValue());
            	item.setHandleStatus(0);
            	item.setMatchUserId(info.get("matchUserId").toString());
            	item.setCreateTime(date);
            	backlogItemRepository.save(item);
            	
            	
            	BacklogItemContract contract = new BacklogItemContract();
            	contract.setMatchUserId(info.get("matchUserId").toString());
            	contract.setBacklogItemId(item.getId());
            	contract.setContractNubmer(info.get("contractNumber").toString());
            	backlogItemContractRepository.save(contract);
            });
    	}catch(Exception e) {
    		log.error("合同到期提醒异常  " + e.getMessage(),e);
    	}
   }
    
}
